import autoinstall
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import requests
import warnings
warnings.filterwarnings('ignore')
plt.rcParams['font.family']='SimHei'
plt.rcParams['axes.unicode_minus']=False
plt.rcParams['figure.figsize']=(12,8)


def get_data(code,start,end):
    '''
    获取指定时间范围的股票数据
    :param code: 指数代码
    :param start: 起始日期
    :param end: 截止日期
    :return: DataFrame
    '''
    url='http://quotes.money.163.com/service/chddata.html?code={}&start={}&end={}&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;VOTURNOVER;VATURNOVER'.format(code,start,end)
    name=code+'_'+start+"-"+end
    f=open(name,'wb')
    f.write(requests.get(url).content)
    f.close()
    data=pd.read_csv(name,encoding='gbk')
    return data

def clean_data(data):
    '''
    1、将日期转换为时间序列并设置为索引
    2、将数据按时间序列升序排序
    3、删除缺失值
    4、将涨跌幅的单位转换为小数
    
    '''
    data['日期']=pd.to_datetime(data['日期'])
    data=data.set_index("日期")
    data=data.sort_index()
    data.drop(data[data["涨跌幅"]=="None"].index,axis=0,inplace=True)
    data["涨跌幅"]=data['涨跌幅'].astype('float')
    data['涨跌幅']/=100
    return data